package com.lovely3x.library.activityies;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.lovely3x.common.activities.CommonActivity;
import com.lovely3x.common.activities.PureHandlerActivity;
import com.lovely3x.common.adapter.BaseViewHolder;
import com.lovely3x.common.adapter.ListAdapter;
import com.lovely3x.common.utils.BitmapSharePool;
import com.lovely3x.common.utils.IntentUtils;
import com.lovely3x.common.utils.blur.Blur;
import com.lovely3x.common.widgets.EnoughHeightGridView;
import com.lovely3x.library.PlatformConst;
import com.lovely3x.library.benas.Platform;
import com.lovely3x.umeng.social.library.BuildConfig;
import com.lovely3x.umeng.social.library.R;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 分享界面
 * Created by lovely3x on 16/8/26.
 */
public class BlurShareActivity extends PureHandlerActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    /**
     * 需要分享的内容
     */
    public static final String EXTRA_SHARE_CONTENT = "extra.share.content";

    /**
     * 分享返回值:分享失败的原因
     */
    public static final String RESULT_EXTRA_ERR_REASON = "extra.err.reason";

    /**
     * 回调对象，用户希望在分享完成后再把这个对象给回传回去时可以通过这个key来传递一些值
     * 这些值必须是可打包的，否则将会出现异常
     */
    public static final String EXTRA_CALLBACK_OBJECT = "extra.callback.object";

    /**
     * 分享返回值:分享的平台
     */
    public static final String RESULT_EXTRA_SHARE_PLATFORM = "result.extra.share.platform";

    public static final int RESULT_FAIL = -3;

    public static final String EXTRA_SHARE_OBJECT_KEY = "extra.share.object.key";

    private static final String SAVE_INSTANCE_KEY_WAITING_SHARE_RESULT = "save.insatnce.key.waiting.share.result";

    private static boolean init;

    private View ivCancel;

    private EnoughHeightGridView ehgvPlatforms;

    private View viewContainer;

    private ListAdapter<Platform> mPlatformsListAdapter;

    private com.lovely3x.library.benas.ShareContent mShareContent;
    private ShareAction mShareAction;
    private Bitmap mBakgroundBm;
    private ImageView mIvBackground;

    private int screenHeight;
    private int perDuration;
    private int perWidth;

    private static final int MAX_DURATION = 1200;

    /**
     * 是否在等待分享结果
     * 如果是在等待分享结果
     * 那么在activity destroy 时就不能释放掉监听器
     */
    private boolean mWaitingShareResult;
    private Object mCallBackObj;

    private static void initIfNeed() {
        if (!init) {
            init = true;
            //微信
            PlatformConfig.setWeixin(BuildConfig.WX_APP_KEY, BuildConfig.WX_SECRET);
            //新浪微博
            PlatformConfig.setSinaWeibo(BuildConfig.SINA_APP_KEY, BuildConfig.SINA_SECRET, "https://api.weibo.com/oauth2/default.html");
            //qq空间
            PlatformConfig.setQQZone(BuildConfig.QQ_APP_ID, BuildConfig.QQ_APP_KEY);
        }
    }

    public BlurShareActivity() {
        initIfNeed();
    }

    public static void launchMe(@NonNull CommonActivity activity, @NonNull com.lovely3x.library.benas.ShareContent shareContent) {
        Intent intent = new Intent(activity, BlurShareActivity.class);
        intent.putExtra(EXTRA_SHARE_CONTENT, shareContent);
        activity.startActivity(intent);
    }

    public static void launchMe(@NonNull CommonActivity activity, @NonNull com.lovely3x.library.benas.ShareContent shareContent, int requestCode) {
        launchMe(activity, shareContent, null, requestCode);
    }

    public static void launchMe(@NonNull CommonActivity activity, @NonNull com.lovely3x.library.benas.ShareContent shareContent, Object callBackExtra, int requestCode) {
        Intent intent = new Intent(activity, BlurShareActivity.class);
        Bundle bundle = activity.buildBundle(EXTRA_SHARE_CONTENT, shareContent, EXTRA_CALLBACK_OBJECT, callBackExtra);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState != null) {
            this.mWaitingShareResult = savedInstanceState.getBoolean(SAVE_INSTANCE_KEY_WAITING_SHARE_RESULT);
        }

        this.mShareContent = getIntent().getParcelableExtra(EXTRA_SHARE_CONTENT);
        this.mCallBackObj = getIntent().getExtras().get(EXTRA_CALLBACK_OBJECT);

        if (mShareContent == null)
            throw new IllegalArgumentException("Share content con't be null.");

        setContentView(getContentView());

        ivCancel = findViewById(R.id.tv_activity_share_cancel);
        ehgvPlatforms = (EnoughHeightGridView) findViewById(R.id.ehgv_activity_share_platforms);
        viewContainer = findViewById(R.id.fl_activity_share_container);

        mIvBackground = (ImageView) findViewById(R.id.iv_activity_share_background);

        ivCancel.setOnClickListener(this);
        viewContainer.setOnClickListener(this);

        ehgvPlatforms.setAdapter(this.mPlatformsListAdapter = createPlatformsListAdapter());

        ehgvPlatforms.setOnItemClickListener(this);

        mBakgroundBm = BitmapSharePool.get(EXTRA_SHARE_OBJECT_KEY);

        if (mIvBackground != null) {
            mIvBackground.setColorFilter(getColor(R.color.light_black_transparent, true));
        }

        if (mBakgroundBm != null) {
            Blur.from(mBakgroundBm).radius(8).scaleDown(20).recycleSrcBitmap(false).into(mIvBackground);
        }

        playEnterAnim();
    }

    protected int getContentView() {
        return R.layout.activity_blur_share;
    }

    protected void playEnterAnim() {
        ehgvPlatforms.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //启动动画
                ehgvPlatforms.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                AnimatorSet visAnimSet = createOpenAnimation(ehgvPlatforms);
                visAnimSet.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                        super.onAnimationStart(animation);
                        playCloseButtonAnim();
                    }

                    private void playCloseButtonAnim() {
                        ObjectAnimator.ofFloat(ivCancel, View.ALPHA, 0, 1).setDuration(MAX_DURATION + MAX_DURATION >> 1).start();
                    }
                });
                visAnimSet.start();
            }
        });
    }


    /**
     * 创建分享平台列表
     */
    protected ListAdapter<Platform> createPlatformsListAdapter() {
        return new PlatformsListAdapter(makePlatforms(), this);
    }

    /**
     * 创建需要分享的平台列表
     *
     * @return
     */
    protected List<Platform> makePlatforms() {
        final ArrayList<Platform> platforms = new ArrayList<>();
        platforms.add(getPlatform(SHARE_MEDIA.WEIXIN));
        platforms.add(getPlatform(SHARE_MEDIA.QZONE));
        platforms.add(getPlatform(SHARE_MEDIA.SINA));
        platforms.add(getPlatform(SHARE_MEDIA.WEIXIN_CIRCLE));

//        platforms.add(getPlatform(SHARE_MEDIA.QQ));
//        platforms.add(getPlatform(SHARE_MEDIA.SMS));
//        platforms.add(getPlatform(SHARE_MEDIA.EMAIL));

        return platforms;
    }

    /**
     * 当取消分享被点击后执行
     */
    public void onCancelClicked() {
        setResult(RESULT_CANCELED);
        playFinishAnim();
    }

    protected void playFinishAnim() {
        AnimatorSet anim = CreateCloseAnimation(ehgvPlatforms);
        //添加动画播放结束监听器
        //动画播放结束后就结束掉当前页面
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationCancel(Animator animation) {
                super.onAnimationCancel(animation);
                finish();
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                finish();
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                //使用动画隐藏关闭按钮
                ObjectAnimator.ofFloat(ivCancel, View.ALPHA, 1, 0).setDuration(100).start();
            }
        });
        anim.start();
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.tv_activity_share_cancel) {
            onCancelClicked();
        } else if (i == R.id.fl_activity_share_container) {//容器
            onCancelClicked();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Platform item = mPlatformsListAdapter.getItem(position);
        doClick(item);
    }

    /**
     * 处理点击事件
     *
     * @param platform
     */
    protected void doClick(Platform platform) {

        SHARE_MEDIA media = getShareMedia(platform);

        if (media != null) {
            assignListener();
            this.mWaitingShareResult = true;

            UMWeb umWeb = new UMWeb(mShareContent.mTargetUrl);
            umWeb.setTitle(mShareContent.mTitle);
            umWeb.setThumb(buildShareImage());
            umWeb.setDescription(mShareContent.mText);

            mShareAction = new ShareAction(BlurShareActivity.this);
            mShareAction.setPlatform(media);
            mShareAction.setCallback(UMShareListener);
            mShareAction.withMedia(umWeb).share();
        }
    }

    private void assignListener() {
        UMShareListener = new UMShareListener() {

            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
                mWaitingShareResult = false;
                if (mShareAction != null) mShareAction.setCallback(null);
                setResult(RESULT_OK, IntentUtils.makeIntent(
                        RESULT_EXTRA_SHARE_PLATFORM, getPlatform(share_media),
                        EXTRA_CALLBACK_OBJECT, mCallBackObj
                ));
                finish();
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                mWaitingShareResult = false;
                if (mShareAction != null) mShareAction.setCallback(null);
                setResult(RESULT_FAIL, IntentUtils.makeIntent(
                        RESULT_EXTRA_ERR_REASON, throwable,
                        RESULT_EXTRA_SHARE_PLATFORM, getPlatform(share_media),
                        EXTRA_CALLBACK_OBJECT, mCallBackObj));
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                mWaitingShareResult = false;
                if (mShareAction != null) mShareAction.setCallback(null);
                setResult(RESULT_CANCELED, IntentUtils.makeIntent(
                        RESULT_EXTRA_SHARE_PLATFORM, getPlatform(share_media),
                        EXTRA_CALLBACK_OBJECT, mCallBackObj));
                finish();
            }
        };
    }

    private SHARE_MEDIA getShareMedia(Platform platform) {
        SHARE_MEDIA media = null;
        switch (platform.id) {
            case PlatformConst.WE_CHAT:
                media = SHARE_MEDIA.WEIXIN;
                break;
            case PlatformConst.Q_ZONE:
                media = SHARE_MEDIA.QZONE;
                break;
            case PlatformConst.QQ:
                media = SHARE_MEDIA.QQ;
                break;
            case PlatformConst.SINA:
                media = SHARE_MEDIA.SINA;
                break;
            case PlatformConst.WE_CHAT_CIRCLE:
                media = SHARE_MEDIA.WEIXIN_CIRCLE;
                break;
        }
        return media;
    }


    private Platform getPlatform(SHARE_MEDIA media) {
        Platform platform = null;
        switch (media) {
            case QQ:
                platform = new Platform(PlatformConst.QQ, getString(R.string.qq), R.drawable.icon_qq);
                break;
            case QZONE:
                platform = new Platform(PlatformConst.Q_ZONE, getString(R.string.q_zone), R.drawable.icon_share_qzone);
                break;
            case WEIXIN_CIRCLE:
                platform = new Platform(PlatformConst.WE_CHAT_CIRCLE, getString(R.string.we_chat_circle), R.drawable.icon_share_circle);
                break;
            case WEIXIN:
                platform = new Platform(PlatformConst.WE_CHAT, getString(R.string.wechat), R.drawable.icon_share_wechat);
                break;
            case SINA:
                platform = new Platform(PlatformConst.SINA, getString(R.string.sina_web), R.drawable.icon_share_sina);
                break;
        }

        return platform;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BitmapSharePool.put(EXTRA_SHARE_OBJECT_KEY, null);//置空

        if (UMShareListener != null && !mWaitingShareResult) {
            if (mShareAction != null) {
                mShareAction.setCallback(null);
            }
            UMShareListener = null;
        }
    }

    /**
     * 创建分享的图片
     *
     * @return
     */
    protected UMImage buildShareImage() {

        if (!TextUtils.isEmpty(mShareContent.imageUrl)) {
            return new UMImage(this, mShareContent.imageUrl);
        } else if (!TextUtils.isEmpty(mShareContent.imageFilePath)) {
            return new UMImage(this, new File(mShareContent.imageFilePath));
        } else if (mShareContent.imageResource > 0) {
            return new UMImage(this, mShareContent.imageResource);
        } else if (mShareContent.bitmap != null) {
            return new UMImage(this, mShareContent.bitmap);
        }

        return null;
    }

    /**
     * 分享平台列表
     */
    public static class PlatformsListAdapter extends ListAdapter<Platform> {

        public PlatformsListAdapter(List<Platform> datas, Context context) {
            super(datas, context);
        }

        @NonNull
        @Override
        public BaseViewHolder createViewHolder(int position, ViewGroup parent) {
            return new ViewHolder(getLayoutInflater().inflate(R.layout.view_platforms_list, parent, false));
        }

        @Override
        public void handleData(int position, @NonNull BaseViewHolder holder) {
            Platform item = getItem(position);
            ViewHolder viewHolder = (ViewHolder) holder;

            viewHolder.icon.setImageResource(item.icon);
            viewHolder.tvName.setText(item.name);
        }

        static class ViewHolder extends BaseViewHolder {

            ImageView icon;

            TextView tvName;

            public ViewHolder(View rootView) {
                super(rootView);
                icon = (ImageView) rootView.findViewById(R.id.iv_view_platforms_list_icon);
                tvName = (TextView) rootView.findViewById(R.id.tv_view_platforms_list_name);
            }
        }
    }

    @Override
    public void applyTranslationStatusBarAndNavigationBar(boolean showStatusBar, boolean showNavigationBar, int statusBarColor, int navigationBarColor, boolean tint, boolean darkMode) {

    }

    @Override
    public void applyTranslationStatusBarAndNavigationBar(Tint tint) {

    }


    private UMShareListener UMShareListener;


    private int getChildNum() {
        return ehgvPlatforms.getAdapter() == null ? 0 : ehgvPlatforms.getAdapter().getCount();
    }

    private AnimatorSet createOpenAnimation(ViewGroup parent) {
        ArrayList<Animator> visAnimList = new ArrayList<Animator>();
        AnimatorSet visAnimSet = new AnimatorSet();

        WindowManager wm = getWindow().getWindowManager();

        int childNum = getChildNum();

        screenHeight = wm.getDefaultDisplay().getHeight();
        perDuration = MAX_DURATION / childNum / 2;
        perWidth = parent.getWidth() / childNum / 2 / 2;

        for (int i = 0; i < childNum; i++) {
            ObjectAnimator itemAnim = createItemVisAnim(ehgvPlatforms.getChildAt(i), i);
            visAnimList.add(itemAnim);
        }
        visAnimSet.playTogether(visAnimList);
        return visAnimSet;
    }

    private AnimatorSet CreateCloseAnimation(ViewGroup parent) {
        ArrayList<Animator> visAnimList = new ArrayList<Animator>();
        AnimatorSet visAnimSet = new AnimatorSet();

        WindowManager wm = getWindow().getWindowManager();

        int childNum = getChildNum();
        screenHeight = wm.getDefaultDisplay().getHeight();
        perDuration = MAX_DURATION / childNum / 2;
        perWidth = parent.getWidth() / childNum / 2 / 2;

        for (int i = 0; i < childNum; i++) {
            ObjectAnimator itemAnim = createItemInvisAnim(ehgvPlatforms.getChildAt(i), i);
            visAnimList.add(itemAnim);
        }
        visAnimSet.playTogether(visAnimList);
        return visAnimSet;
    }

    //显示动画
    private ObjectAnimator createItemVisAnim(final View target, int index) {

        ObjectAnimator invisToVis = null;
        target.setPivotX(perWidth * index);
        target.setPivotY(screenHeight * 1.2f);
        invisToVis = ObjectAnimator.ofFloat(target, "translationY", screenHeight * 1.2f, target.getHeight() / 2);
        invisToVis.setDuration(MAX_DURATION - perDuration * (getChildNum() - 1 - index));
        invisToVis.setInterpolator(new AnticipateOvershootInterpolator(1f));
        invisToVis.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                target.setVisibility(View.VISIBLE);
            }
        });

        return invisToVis;
    }

    //隐藏动画
    private ObjectAnimator createItemInvisAnim(final View target, int index) {
        target.setPivotX(perWidth * index);
        target.setPivotY(target.getHeight() / 2);
        ObjectAnimator visToInvis = ObjectAnimator.ofFloat(target, "translationY", target.getHeight() / 2, screenHeight * 1.2f);
        visToInvis.setDuration(perDuration + perDuration * (getChildNum() - index));
        visToInvis.setInterpolator(new AccelerateInterpolator(2f));

        return visToInvis;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(SAVE_INSTANCE_KEY_WAITING_SHARE_RESULT, mWaitingShareResult);
    }
}
